<template>
  <view class="container" style="padding-bottom: 100px" v-if="isLoaded">
    <view class="content" style="padding: 30rpx 30rpx 120rpx; background-color: #fff">
      <!-- 编辑模式 -->
      <li-form v-if="mode == 'edit'">
        <!--         <li-form-item label="用户名">
          <li-input
            v-model="form.userName"
            rule="trim"
            prop="userName"
            disabled
            @blur="onBlurEvent($event)"
          />
        </li-form-item> -->
        <li-form-item label="上级店铺">
          <li-picker v-model="form.parentStoreId" :rangeList="parentStoreList" rangeKey="storeName" />
        </li-form-item>

        <li-form-item label="门店名称" required>
          <li-input v-model="form.storeName" rule="trim" prop="storeName" @blur="onBlurEvent($event)" />
        </li-form-item>
        <li-form-item label="门店电话">
          <li-input v-model="form.mobile" rule="trim" prop="mobile" @blur="onBlurEvent($event)" />
        </li-form-item>
        <li-form-item label="所属行业">
          <li-picker v-model="form.industryId" :rangeList="IndustryList" :rangeKey="'name'" />
        </li-form-item>
        <li-form-item label="支付账号">
          <li-input v-model="form.payAccount" rule="trim" prop="payAccount" @blur="onBlurEvent($event)" />
        </li-form-item>
        <li-form-item label="门店联系人">
          <li-input v-model="form.linkMan" rule="trim" prop="linkMan" @blur="onBlurEvent($event)" />
        </li-form-item>

        <li-form-item label="所属区域" :border="false">
          <view style="background-color: #fff">
            <uni-data-picker :localdata="areaList" popup-title="请选择区域" @change="onchange" :value="formatAreaObj" />
          </view>
        </li-form-item>
        <li-form-item label="门店地址" required>
          <li-input v-model="form.address" rule="trim" prop="address" @blur="onBlurEvent($event)" />
        </li-form-item>
      </li-form>
      <!-- 新增模式 -->
      <li-form v-else>
        <li-form-item label="上级商户">
          <li-picker v-model="form.parentStoreId" :rangeList="parentStoreList" rangeKey="storeName" />
        </li-form-item>
        <li-form-item label="创建激活码">
          <li-picker v-model="form.isCreateFacCode" :range-list="booleanEnum"></li-picker>
        </li-form-item>
        <li-form-item label="默认密码" required>
          <li-input v-model="form.passWord" password placeholder="请输入默认密码" prop="passWord" />
        </li-form-item>
        <li-form-item class="fs12" label="连续新增数量">
          <li-input v-model="form.createCount" rule="int" prop="createCount" />
        </li-form-item>
        <li-form-item label="有效日期">
          <li-date-picker v-model="form.endDate" prop="endDate" />
        </li-form-item>
      </li-form>
    </view>

    <view class="bottom-btn" v-on:click="btnEditOrSaveSubmitClick">保存</view>
  </view>
</template>
<script>
import liFormMixin from '../../../mixins/liFormMixin';
import { DelStoreById, AddStore, GetStoreById, EditStore, GetCoreCmsStoreList, GetIndustryList, DoCreateByGroup } from '../../../common/modules/m.js';
import { liChecker } from '@/common/graceChecker';
import { transferTypeEnum, transfer } from '../../../common/dataTransfer.js';
import { checkerType, modeEnum, booleanEnum, areaList } from '../../../constants/normalConstants.js';
import { corpId, storeId } from '../../../constants/apiConstants.js';
import { toastIconEnum } from '../../../constants/uiConstants.js';
import { uHideLoading, uShowLoading, utoast, uNavigateBack, umodal, uNavigateTo } from '@/utils/uniUtils';

export default {
  mixins: [liFormMixin],
  async onLoad(options) {
    this.loadEvent(options, this);
  },

  async mounted() {
    try {
      uShowLoading();
      this.parentStoreList = (
        await GetCoreCmsStoreList({
          pageNum: 1,
          pageSize: 9999,
          isGroup: 1
        })
      ).data.list;
      this.parentStoreList = [
        {
          id: 0,
          storeName: '无上级店铺'
        },
        ...this.parentStoreList
      ];
      if (this.mode == modeEnum.edit) {
        await this.getData();
        const areaNameArr = this.form.areaFullName.split(' ');
        this.formatAreaObj =
          areaNameArr.length > 0
            ? [
                {
                  text: areaNameArr[0],
                  value: this.form.provinceId.toString()
                },
                {
                  text: areaNameArr[1],
                  value: this.form.cityId.toString()
                },
                {
                  text: areaNameArr[2],
                  value: this.form.areaId.toString()
                }
              ]
            : [
                {
                  text: 0,
                  value: '无'
                },
                {
                  text: 0,
                  value: '无'
                },
                {
                  text: 0,
                  value: '无'
                }
              ];
        this.getOtherData();
      } else {
        const today = new Date();
        this.form = {
          parentStoreId: 0,
          isCreateFacCode: true,
          createCount: 1,
          endDate: `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate() + 1}`,
          passWord: ''
        };
      }

      this.isLoaded = true;
    } catch (error) {
      console.log('error', error);
      utoast('初始化失败~', toastIconEnum.error);
      setTimeout(() => {
        uNavigateBack();
      }, 800);
    } finally {
      uHideLoading();
    }
  },
  data() {
    return {
      areaList,
      modeEnum,
      booleanEnum,
      IndustryList: [],
      parentStoreList: [],
      subject: '门店', // 主题
      rootRoute: 'workbench',
      routeName: 'merchant',
      mode: 'edit', // 模式
      isLoaded: false,
      id: null,
      /* 表单 */
      form: null,
      formatAreaObj: [],
      /* 弹窗 */

      // 数据转换器
      transferRules: [
        /*   {
            name: "depositMoney",
            type: transferTypeEnum.float,
          },
       */
      ],
      //表单校验规则
      rules: [
        {
          name: 'storeName',
          checkType: checkerType.endNotNull,
          errorMsg: '店铺名不能为空'
        },
        {
          name: 'address',
          checkType: checkerType.endNotNull,
          errorMsg: '地址不能为空'
        }
      ],
      lock: false, // 节流锁

      /* 额外数据 */
      DepartmentList: []
      /* 额外校验规则 */

      /* 额外转换器 */
    };
  },

  methods: {
    onBlurEvent(e) {
      this.formBlur(e, this);
    },

    async getData() {
      this.form = (await GetStoreById(this.id)).data;
    },

    async getOtherData() {
      this.IndustryList = (await GetIndustryList()).data;
    },

    async insertData() {
      return DoCreateByGroup(this.form);
    },

    async delData() {
      return await DelStoreById(this.id);
    },

    async editData() {
      return await EditStore(this.form);
    },

    async btnDelClick() {
      await this.formDelete(this);
    },

    async btnEditOrSaveSubmitClick() {
      if (this.lock) {
        return;
      }

      if (!(await umodal('确认要提交吗？'))) {
        return;
      }
      if (this.mode == modeEnum.edit) {
        this.form = transfer(this.form, this.transferRules);

        let isOk = liChecker.check(this.form, this.rules);
        if (!isOk) {
          await utoast(liChecker.error, toastIconEnum.none);
          return;
        }
      } else {
        if (this.form.createCount < 1) {
          utoast('新增数量必须为正数', toastIconEnum.none);
          return;
        }
        if (this.form.passWord.trim().length < 1) {
          utoast('密码不能为空', toastIconEnum.none);
          return;
        }
      }

      const res = this.mode == modeEnum.edit ? await this.editData(this.form) : await this.insertData(this.form);
      if (res?.code == 0) {
        await utoast('操作成功');
        setTimeout(() => {
          uNavigateTo(`/pages/${this.rootRoute}/${this.routeName}/list`);
        }, 1000);
      } else {
        setTimeout(() => {
          this.lock = false;
        }, 2000);
      }
    },
    onchange(e) {
      this.formatAreaObj = e.detail.value;
      let areaObj = [];
      if (this.formatAreaObj.length == 0) {
        areaObj = [0, 0, 0];
      } else {
        this.formatAreaObj.forEach((element) => {
          areaObj.push(element.value);
        });
      }
      this.form.areaObject = areaObj;
      this.form.provinceId = areaObj[0];
      this.form.cityId = areaObj[1];
      this.form.areaId = areaObj[2];
    }
    /* 额外方法放下面，上面是主干方法 */

    //方法放上面
  }
};
</script>
<style lang="scss" scoped>
@import '~@/static/styles/commonStyle.scss';

.bottom-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #fdc31d;
  color: #fff;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  letter-spacing: 3px;
}
</style>
